package com.isyscore.os.metadata.service.executor;

import com.isyscore.boot.login.LoginUserManager;
import com.isyscore.os.core.util.ApplicationUtils;
import com.isyscore.os.core.util.InitiallyUtils;
import com.isyscore.os.metadata.enums.TaskPeriodUnit;
import com.isyscore.os.metadata.model.entity.Metric;
import com.isyscore.os.metadata.service.impl.MetricCalculateService;
import com.isyscore.os.metadata.service.impl.MetricService;
import com.isyscore.os.metadata.utils.CronUtils;
import com.isyscore.os.permission.entity.LoginVO;
import lombok.extern.slf4j.Slf4j;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * @author liy
 * @date 2023-09-04 17:05
 */
@Slf4j
public class MetricJobTaskExecutor  extends BaseExecutor{
    private static final LoginUserManager loginUserManager = ApplicationUtils.getBean(LoginUserManager.class);
    private static final MetricService metricService = ApplicationUtils.getBean(MetricService.class);
    private static final MetricCalculateService metricCalculateService = ApplicationUtils.getBean(MetricCalculateService.class);
    private static final Set<Long> runningFlow = Collections.synchronizedSet(new HashSet<>());
    private final Long metricId;
    private final Metric metric;
    public MetricJobTaskExecutor(Long metricId){
        this.metricId = metricId;
        metric = InitiallyUtils.markIgnore(() -> metricService.getFullMetricInfoById(metricId));
    }
    @Override
    protected void runJob() {
        Metric metric = InitiallyUtils.markIgnore(() -> metricService.getMetricById(metricId));
        LoginVO loginVO = new LoginVO();
        loginVO.setTenantId(metric.getTenantId());
        runningFlow.add(metricId);
        //将当前租户设置为对应指标的租户ID
        try {
            loginUserManager.executeWithAssignedLoginUser(loginVO, () -> {
                metricCalculateService.calculateMetricWithLog(metricId, null, null);
                return null;
            });
        }catch (Exception e){
           log.error("指标任务运行异常{}",metricId,e);
        }finally {
            runningFlow.remove(metricId);
        }
    }

    @Override
    public boolean jobIsRunning() {
        return runningFlow.contains(metricId);
    }

    @Override
    TaskPeriodUnit getTaskPeriodUnit() {
        return CronUtils.getCornPeriod( metric.getTaskCron());
    }

}
